import { config } from "@/config";
import { PrefixType } from "@/types/common";
import serve from "@/serve/_";
import moment from 'moment'

export const setItem = (key: string, value: any): void => {
    localStorage.setItem(
        key,
        value.constructor == Object || value.constructor == Array
            ? JSON.stringify(value)
            : value
    )
}

export const getItem = (key: string): [] | {} | any => {
    return localStorage.getItem(key) == null ? false : JSON.parse(<string>localStorage.getItem(key))
}

export const isPhone = (phone: string): boolean => {
    let myreg = /^1[3-9]\d{9}$/;
    return myreg.test(phone)
}

export const format = (time: Date | number | string, fmt: string): string => {
    return moment(time).format(fmt);
}

export const injectBaseUrl = () => {
    for (const key in serve) {
        if (isValidKey(key, serve)) {
            const methods: Function = serve[key];
            console.log("methods",methods.name)
            methods.prototype = {}
            
            serve[methods.name.split("_")[1]] = methods

            let vvv:PrefixType =<PrefixType> methods.name.split("_")[1]
            let BaseUrlPrefix: PrefixType = <PrefixType>methods.name.split("_")[0]
            if(import.meta.env.MODE == "development"){
                methods.prototype.base = config.baseUrl[BaseUrlPrefix].devBaseUrl
                methods.prototype.url = config.apiList[BaseUrlPrefix][vvv]
                console.log(config.apiList[BaseUrlPrefix][vvv])
            }else{
                methods.prototype.url = config.baseUrl[BaseUrlPrefix].prodBaseUrl
                console.log(2)
            }
        }
    }

    return serve
}

export default injectBaseUrl()


function isValidKey(key: string | number | symbol, object: object): key is keyof typeof object {
    return key in object;
}
